<template>
  <div>
    <el-table v-model="tableData" :data="tableData" stripe style="width: 100%">
      <el-table-column prop="account" label="账号" width="180" />
      <el-table-column prop="mobile" label="手机号" width="180" />
      <el-table-column prop="avatar" label="头像">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" width="90">
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 1 ? '正常' : '封禁' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updated_at" label="时间">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.updated_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">修改信息</el-button>
          <!-- <el-button type="danger" size="mini" @click="handpassword(scope.row)">修改密码</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog width="50%" title="修改信息" :visible.sync="dialogVisible">
      <el-form ref="form" :model="formData" :inline="true" label-width="100px">
        <el-form-item label="手机号">
          <div style="margin: 1px 0" />
          <el-input v-model="formData.mobile" />
        </el-form-item>
        <div style="margin: 1px 0" />
        <el-form-item label="姓名">
          <el-input v-model="formData.username" />
        </el-form-item>
        <div style="margin: 1px 0" />
        <el-form-item label="新密码" prop="password">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>
        <div style="margin: 1px 0" />
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :headers="{ Authorization: token }" :action="uploadUrl" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-error="handleAvatarError" list-type="picture-card">
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog width="50%" title="修改密码" :visible.sync="diaPassword">
      <el-form ref="form" :model="formppassword" :inline="true" :rules="rules">
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="formppassword.password" type="password" />
        </el-form-item>
        <div style="margin: 1px 0" />
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="formppassword.old_password" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="diaPassword = false">取消</el-button>
        <el-button type="primary" @click="hanPassword">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { postUsser, updataUser, postUser } from '@/api/Infor'
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      uploadUrl: '/asd_wqdc_api/admin/file/upload', // 上传接口的 URL
      dialogVisible: false, // 个人信息弹窗
      diaPassword: false, // 修改密码弹窗
      currentIndex: -1, // 初始化时没有选中任何行
      token: Cookies.get('token'),
      formData: {
        mobile: '',
        username: '',
        avatar: '',
        password: ''
      },
      formppassword: {
        old_password: '',
        new_password: ''
      },

      tableData: [],
      rules: {
        new_password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        old_password: [{ required: true, message: '请输入旧密码' }]
      }
    }
  },
  mounted() {
    // console.log(this.token, 'token');
    // 发送获取信用列表数据的请求
    postUsser()
      .then((data) => {
        console.log(data.data.data, 'data11111111111')
        this.tableData.push(data.data.user)
        console.log(this.tableData, 'data22222222222')
      })
      .catch((error) => {
        console.error(error)
      })
  },
  methods: {
    onel() {
      this.$refs.form.resetFields()
    },
    handleEdit(row) {
      this.currentIndex = this.tableData.indexOf(row) // 获取该行的索引
      this.formData = Object.assign({}, row) // 使用 Object.assign 复制该行的属性（避免直接引用）
      this.dialogVisible = true
    },
    handpassword(row) {
      this.diaPassword = true
    },
    formatDate(timestamp) {
      if (timestamp) {
        const date = new Date(timestamp)
        return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-')
      }

      return ''
    },
    // 修改个人密码
    hanPassword() {
      postUser(this.formppassword)
        .then((data) => {
          this.$message.error(data.data.message) // 添加错误提示
        })
        .catch((data) => {})
      this.diaPassword = false
      this.onel()
    },
    // 修改个人信息
    handleSave() {
      this.tableData.splice(this.currentIndex, 1, this.formData) // 使用该行的索引替换表格中的原始数据
      updataUser(this.formData)
        .then((data) => {
          console.log(data.data.data, 'data11111111111')
        })
        .catch((data) => {
          console.error(data.message)
        })

      // ...
      this.dialogVisible = false
    },
    // 上传图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return isJPG || (isPNG && isLt2M)
    },
    handleAvatarSuccess(response, file) {
      const { data } = response // 获取服务端返回的头像 URL
      const baseUrl = 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/16975354959389.png/' // 去掉固定的 URL 部分
      const imgUrl = data.replace(baseUrl, 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/', '') // 去掉固定部分的 URL，并添加新的URL
      this.formData.avatar = imgUrl // 设置修改后的图片 URL
      this.$message.success('头像上传成功！')
    },
    handleAvatarError() {
      this.$message.error('头像上传失败！')
    }
  }
}
</script>
<style scoped>
.el-upload img {
  width: 100%;
  height: 100%;
}
</style>
